<?php

namespace App\Core;

use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Config;
use EasySwoole\Log\LoggerInterface;
use EasySwoole\RedisPool\RedisPool;

class Logger implements LoggerInterface{

    use Singleton;

    function log(?string $msg, int $logLevel = self::LOG_LEVEL_DEBUG, string $category = 'debug'){
        $prefix = date('Ymd');
        $date = date('Y-m-d H:i:s');
        $levelStr = $this->levelMap($logLevel);
        if(empty(Config::getInstance()->getConf('LOG.dir'))){
            $logDir = getcwd();
        } else {
            $logDir = EASYSWOOLE_LOG_DIR;
        }
        $filePath = $logDir . "/{$category}_{$prefix}.log";
        $str = "[{$date}][{$category}][{$levelStr}]:[{$msg}]\n";
        file_put_contents($filePath, "{$str}", FILE_APPEND | LOCK_EX);
        //本地开发环境不推送ELK
//        if (Config::getInstance()->getConf('ENV') != 'dev') {
//            $redis = RedisPool::defer();
//            $redis->lpush('warehouse_log',$str);
//        }
        return $str;
    }
    
    function console(?string $msg, int $logLevel = self::LOG_LEVEL_DEBUG, string $category = 'debug'){
        $date = date('Y-m-d H:i:s');
        $levelStr = $this->levelMap($logLevel);
        echo "[{$date}][" . getmypid() . "][][{$category}][{$levelStr}]:[{$msg}]\n";
    }
    
    private function levelMap(int $level){
        switch($level){
            case self::LOG_LEVEL_DEBUG:
                return 'debug';
            case self::LOG_LEVEL_INFO:
                return 'info';
            case self::LOG_LEVEL_NOTICE:
                return 'notice';
            case self::LOG_LEVEL_WARNING:
                return 'warning';
            case self::LOG_LEVEL_ERROR:
                return 'error';
            default:
                return 'unknown';
        }
    }

    public function debug(?string $msg, string $category = 'debug')
    {
        $this->log($msg, LoggerInterface::LOG_LEVEL_DEBUG, $category);
    }

    public function info(?string $msg, string $category = 'info')
    {
        $this->log($msg, LoggerInterface::LOG_LEVEL_INFO, $category);
    }

    public function notice(?string $msg, string $category = 'notice')
    {
        $this->log($msg, LoggerInterface::LOG_LEVEL_NOTICE, $category);
    }

    public function waring(?string $msg, string $category = 'waring')
    {
        $this->log($msg, LoggerInterface::LOG_LEVEL_WARNING, $category);
    }

    public function error(?string $msg, string $category = 'error')
    {
        $this->log($msg, LoggerInterface::LOG_LEVEL_ERROR, $category);
    }
}